package com.horsen.service.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.horsen.service.edu.mapper.SubjectMapper;
import com.horsen.service.edu.model.BO.SubjectInputBO;
import com.horsen.service.edu.model.Subject;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 科目 Excel读取监听器
 *
 * @author Horsen
 */
@Slf4j
@AllArgsConstructor
@NoArgsConstructor
public class SubjectExcelListener extends AnalysisEventListener<SubjectInputBO> {

    private SubjectMapper subjectMapper;

    /**
     * 解析每一条数据时都调用
     *
     * @param data    一条记录
     * @param context 上下文
     */
    @Override
    public void invoke(SubjectInputBO data, AnalysisContext context) {
        log.info("解析到一条记录: {}", data);
        // 处理读取出来的数据
        String primaryTitle = data.getPrimaryTitle();
        String secondaryTitle = data.getSecondaryTitle();
        // 判断一级分类是否重复
        Subject primarySubject = getPrimaryTitle(primaryTitle);
        String parentId;
        if (primarySubject == null) {
            Subject subject = new Subject().setTitle(primaryTitle).setParentId("0");
            subjectMapper.insert(subject);
            parentId = subject.getId();
        } else {
            parentId = primarySubject.getId();
        }
        // 判断二级分类是否重复
        Subject secondarySubject = getSecondaryTitle(secondaryTitle, parentId);
        if (secondarySubject == null) {
            subjectMapper.insert(new Subject().setTitle(secondaryTitle).setParentId(parentId));
        }
    }

    /**
     * 所有数据解析完成时调用
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("所有数据解析完成！");
    }

    /**
     * 获取一级分类
     *
     * @param title 科目名称
     * @return 科目对象
     */
    public Subject getPrimaryTitle(String title) {
        LambdaQueryWrapper<Subject> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Subject::getTitle, title)
                .eq(Subject::getParentId, "0");
        return subjectMapper.selectOne(queryWrapper);
    }

    /**
     * 获取二级分类
     *
     * @param title    科目名称
     * @param parentId 父ID
     * @return 科目对象
     */
    public Subject getSecondaryTitle(String title, String parentId) {
        LambdaQueryWrapper<Subject> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Subject::getTitle, title)
                .eq(Subject::getParentId, parentId);
        return subjectMapper.selectOne(queryWrapper);
    }
}
